package top.xchch.tool.lambda;

import lombok.AllArgsConstructor;
import lombok.Data;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author sai.zhang
 * @date 2021-12-05 12:27
 */
@Data
@AllArgsConstructor
public class Student {
    private String name;
    private Integer age;

    /**
     * lambda toMap key相同时会抛出异常
     */
    @Test
    public void test01() {
        Student zhang3 = new Student("zhang3", 12);
        Student zhang32 = new Student("zhang3", 13);
        Student li4 = new Student("li4", 14);

        List<Student> list = Arrays.asList(zhang3, zhang32, li4);

        // 报错 IllegalStateException: Duplicate key 12
        Map<String, Integer> collect =
                list.stream().collect(Collectors.toMap(Student::getName, Student::getAge));
        System.out.println(collect.size());
    }
}
